//////////////////////////////////////////////////////////////
/////////   Teensy Token core functions 11/2012    ///////////
//////////////////////////////////////////////////////////////

void TimeSync()     // echo T$(($(date +%s))) > /dev/ttyACM0
{
    while(Serial.available() >=  TIME_MSG_LEN ) { 
        char c = Serial.read() ;
        Serial.print(c);
        if( c == TIME_HEADER ) {
            time_t pctime = 0;
            for(int i=0; i < TIME_MSG_LEN -1; i++) {
                c = Serial.read();
                if( c >= '0' && c <= '9') {
                    pctime = (10 * pctime) + (c - '0') ;
                }
            }
            setTime(pctime);  
        }
    }
}

void printHash(uint8_t* hash, int length) {
  int i;
  for (i=0; i<length; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void ProcessKey(){
  uint8_t* hash;
  uint8_t otp[4];
  uint32_t epoch = now() / 30;
  time[4] = (byte )((epoch >> 24));
  time[5] = (byte )((epoch >> 16));
  time[6] = (byte )((epoch >> 8));
  time[7] = (byte )((epoch ));
  Sha1.initHmac(Key, 10);
  Sha1.writebytes(time, 8);
  hash = Sha1.resultHmac();
  memset(otp,0,4);
  int offset = hash[19] & 0x0F;
  memcpy(otp, hash + offset, 4);
  uint32_t val = ((long )otp[0] & 0x7F) << 24;
  val |= ((long )otp[1]) << 16;
  val |= ((long )otp[2]) << 8;
  val |= otp[3];
  val = val % 1000000;
  Send.key = val;
}

void BlinkLED(){
  digitalWrite(LED_PIN, HIGH);
  delay(250);
  digitalWrite(LED_PIN, LOW);
  delay(250);
  digitalWrite(LED_PIN, HIGH);
  delay(250);
  digitalWrite(LED_PIN, LOW);
  delay(250);
  digitalWrite(LED_PIN, HIGH);
  delay(250);
  digitalWrite(LED_PIN, LOW);
  delay(250);
  digitalWrite(LED_PIN, HIGH);
  delay(250);
  digitalWrite(LED_PIN, LOW);
  delay(250);
  digitalWrite(LED_PIN, HIGH);
  delay(250);
  digitalWrite(LED_PIN, LOW);
}
